package com.authority;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.authority.common.AdminConstants;

public class SessionFilter extends OncePerRequestFilter {
	protected static Log logger = LogFactory.getLog(SessionFilter.class);
	private String encoding;

	private boolean forceEncoding = false;

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public void setForceEncoding(boolean forceEncoding) {
		this.forceEncoding = forceEncoding;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
			request.setCharacterEncoding(this.encoding);
			if (this.forceEncoding) {
				response.setCharacterEncoding(this.encoding);
			}
		}
		doFilterSession(request, response, filterChain);
	}

	public void doFilterSession(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		String virtualpath = "";
		if (req.getContextPath() != null && !req.getContextPath().isEmpty())
			virtualpath = req.getContextPath();
		String url = req.getRequestURI().trim();
		if (session.getAttribute("username") == null && !url.contains("login")) {
			if (!res.isCommitted()) {
				res.sendRedirect(virtualpath + "/login/nologin.html");
			}
			return;
		}
		if (url.endsWith(".html") || url.endsWith(".htm"))
			try {
				chain.doFilter(request, response);
			} catch (Exception e) {
				logger.debug(e);
			}
		else if (url.contains("/css/") || url.contains("/js/") || url.contains("/img/") || url.contains("/noCheck_")
				|| url.contains("/yiji/notify")) {
			chain.doFilter(request, response);
		} else if (url.equals(virtualpath + "/login/login.html")) {
			// 登录页面
			chain.doFilter(request, response);
		} else if (url.equals(virtualpath + "/userManager/resetPassword.json")
				|| url.equals(virtualpath + "/userManager/changePassword.json")) {
			// 重替换密码
			chain.doFilter(request, response);
		} else if (url.equals(virtualpath + "/userManager/login.json")
				|| url.equals(virtualpath + "/userManager/loginService.json")
				|| url.equals(virtualpath + "/userManager/logout.json")
				|| url.equals(virtualpath + "/userManager/getMenu.json")
				|| url.equals(virtualpath + "/userManager/getUserName.json")) {
			// 登陆
			chain.doFilter(request, response);
		} else if (url.equals(virtualpath + "/errorpage/404.html")) {
			// 没有权限页面
			chain.doFilter(request, response);
		} else if (session.getAttribute("token") == null || session.getAttribute("username") == null) {
			if (!res.isCommitted()) {
				res.sendRedirect(virtualpath + "/login/login.html");
			}
		} else {
			String urls = String.valueOf(session.getAttribute("userPrivilegeUrls"));
			String uri = req.getRequestURI().trim();
			String ContextUrl = req.getContextPath();
			String[] authorityUrl = urls.split(",");
			boolean hasAuthority = false;
			if (AdminConstants.ADMIN.equals(session.getAttribute("username"))) {
				hasAuthority = true;
			} else {
				out: for (String url2 : authorityUrl) {
					url2 = new StringBuffer().append(ContextUrl).append(url2.trim()).toString();
					if (uri.trim().equals(url2.trim())) {
						hasAuthority = true;
						break out;
					}
				}
			}
			if (!hasAuthority) {
				if (!res.isCommitted()) {
					res.sendRedirect(virtualpath + "/errorpage/404.html");
				}
			} else {
				chain.doFilter(request, response);
			}

		}
	}

}
